import subprocess
import os
from sqlite3_model import *
import sqlite3_operation
import json
import shutil
import plistlib

from code_sync import mw_sync, mp_sync, git_op

def excute_shell(command, path=None, pipe_out=True):
    """
    执行shell脚本
    :param command: 命令行
    :param path: 执行命令行时所在路径，默认当前路径
    :return:
    """
    stderr, stdout = (None, None)
    if pipe_out:
        stderr, stdout = (subprocess.PIPE, subprocess.PIPE)
    result = subprocess.run(command, shell=True, stderr=stderr, stdout=stdout, text=True, cwd=path)
    desc = result.stdout
    if result.returncode != 0:
        desc = result.stderr
    print("python日志 \n执行脚本命令: %s  \n结果: %s" % (command, desc))
    return (result.returncode, desc)

def do_sync_source_code(configId):
    """
    同步代码
    根据configId查询sqlite数据库的同步配置来同步对应的代码
    """
    cur_path = os.getcwd()
    
    pack_config = PackageConfig.get(PackageConfig.id == configId)
    app_item = MostOneAppItem.get(MostOneAppItem.id == pack_config.app_info_id)
    reposity = app_item.reposity
    if reposity is None:
        reposity = "origin"
    
    pro_dir_path = os.path.dirname(pack_config.project_path)
    if os.path.exists(pro_dir_path) is False:
        os.makedirs(pro_dir_path)
        cmd = "git clone --branch %s %s %s" % (pack_config.branch, app_item.git_url, pro_dir_path)
        os.system(cmd)
    
    os.chdir(pack_config.project_path)
    # if os.path.exists(pack_config.project_path) is True:
    #     cmd = "git reset --hard"
    #     os.system(cmd)
        
    #     git_op.git_branch_switch(pack_config.project_path, pack_config.branch)
        
    cmd = "git fetch %s" % (reposity)
    os.system(cmd)
        
    cmd = "git merge %s/%s" % (reposity, pack_config.branch)
    os.system(cmd)
        
    os.chdir(cur_path)

def do_package(configId):
    """
    项目打包
    根据configId查询sqlie数据库的打包配置来打对应的包
    """
    
    pack_config = PackageConfig.get(PackageConfig.id == configId)
  
    if pack_config.schema is None:
        pack_config.schema = pack_config.project_name
        
    if pack_config.ipa_path is None:
        pack_config.ipa_path="/Users/mac/Desktop/LocalIpas/xqt/debug/"
    
    project_path = pack_config.project_path

    # 1. pod install
    os.chdir(project_path)
    cmd = "pod install --verbose"
    os.system(cmd)
    
    # 2. 编译
    os.chdir(project_path)
    cmd = "xcodebuild build -workspace %s.xcworkspace -scheme %s -configuration Debug" % (pack_config.workspace_name, pack_config.schema)
    os.system(cmd)
    
    # 3. 打包
    os.chdir(project_path)
    app_name = pack_config.schema + '.app'
    with open(pack_config.env_config_path, 'r') as file:
        env_config_data = json.load(file)
        build_dir_path = env_config_data['BUILD_DIR']
        file.close()
        
    app_path = os.path.join(build_dir_path, 'Build/Products/Debug-iphoneos', app_name)
    
    current_file_path = os.path.abspath(__file__)
    script_dir = os.path.dirname(current_file_path)
    
    temp_path = os.path.join(script_dir, 'temp')
    payload_path = os.path.join(temp_path, 'Payload')
    payload_app_path = os.path.join(payload_path, app_name)
    
    if os.path.exists(temp_path):
        shutil.rmtree(temp_path)
        
    os.makedirs(temp_path)
    shutil.copytree(app_path, payload_app_path)
    
    ipa_path = shutil.make_archive(payload_path, 'zip', temp_path)
    ipa_path = shutil.move(ipa_path, pack_config.ipa_path + pack_config.schema + '.ipa')
    
    shutil.rmtree(temp_path)
    
    
def generate_manifest(configId, dstdir=''):
    """生成对应的manifest.plist文件"""
    
    pack_config = PackageConfig.get(PackageConfig.id == configId)
    app_item = MostOneAppItem.get(MostOneAppItem.id == pack_config.app_info_id)
    
    manifest = {
        'items': [
            {
                'assets': [
                    {
                        'kind': 'software-package', 
                        'url': pack_config.ipa_url,      
                    },
                    {
                        'kind':'display-image',
                        'url': pack_config.full_image_url,
                    },
                    {
                        'kind':'full-size-image',
                        'url': pack_config.full_image_url,
                    }
                ],
                'metadata': {
                    'bundle-identifier': app_item.bundle_id,
                    'bundle-version': pack_config.version,
                    'kind': 'software',
                    'platform-identifier': 'com.apple.platform.iphoneos',
                    'title': pack_config.title,
                }   
            }
        ]
    }
    
    name = 'manifest_' + app_item.appname
    if pack_config.configuration == 'Debug':
        name = name + '_debug'
    if pack_config.version is not None:
        name = name + '_' + pack_config.version
    name = name + '.plist'    
    
    dst = os.path.join(dstdir, name)
    
    with open(dst, 'wb') as f:
        plistlib.dump(manifest, f)
    
    print("生成manifest.plist文件成功: " + dst)
    
    
def test():
    print("test...")
    
    
    
def mw_pack():
    """
    打包默往项目
    """
    mw_sync.sync_code('/Users/mac/Desktop/GitProjectPackage/Mostone/Project/MostOne')
    do_package(9) #mw
    # do_package(12) #工程路径下
    
def mp_pack(pack_local=False):
    """
    打包默往企业版项目
    """
    if pack_local:
        do_package(14) #mp
    else:
        mp_sync.sync_code('/Users/mac/Desktop/GitProjectPackage/MOPro')
        do_package(10) #mp
    
if __name__ == "__main__":
    
    #excute_shell("ls -l", path='/Users/mac/Documents/cfwifine/python/FlaskProj')
    
    # current_file_path = os.path.abspath(__file__)
    # print(current_file_path)
    # dir = os.path.dirname(current_file_path)
    # print(dir)
    
    
    # do_package(1)
    
    db.connect()
    db.create_tables([MostOneAppItem, PackageConfig])
    
    ########创建一个app##########
    # app = MostOneAppItem.create(
    #     id = 3,
    #     appname="长信",
    #     bundle_id="com.cfwifin.cxap",
    #     test = "长信测试"
    # )
    # app.save()

    ########创建一个乡企通的打包配置##########
    # pkgConfig = PackageConfig.create(
    #     id = 3,
    #     project_path="/Users/mac/Documents/mowan/project/BeastIOS/WCImApp",
    #     project_name="WCImApp",
    #     workspace_name="WCImApp",
    #     configuration="Debug",
    #     env_config_path="/Users/mac/Documents/mowan/project/BeastIOS/WCImApp/build_env_config.json",
    #     app_info_id = 3,
        
    #     ipa_path="/Users/mac/Desktop/LocalIpas/cx/debug/",
    #     ipa_url="http://192.168.199.103:9998/Desktop/LocalIpas/cx/debug/WCImApp.ipa",
    #     full_image_url="https://app-distribution-1310744949.cos.ap-shanghai.myqcloud.com/cfwifine/cx_logo.png",
    #     version="1.0.0",
    #     title="长信"
    # )
    # pkgConfig.save()
   
    ########查询package###########
    # pkg = PackageConfig.get(PackageConfig.id == 1)
    # print(pkg.project_path, pkg.schema, pkg.configuration)
    
    ########生成manifest文件#######
    #generate_manifest(1, dstdir='/Users/mac/Desktop/LocalIpas/manifests/')
    
    ########打包#######
    #打包
    # do_package(1) #xqt
    
    # do_package(2) #jx
    
    # do_package(3) #cx
    
    # do_sync_source_code(7) #jrzx
    # do_package(7) #远程仓库
    
    # do_package(8) #jrzx本地项目目录
    
    # mw_pack() #mw
    
    mp_pack(pack_local=True) #mp
    
    # do_sync_source_code(13) #jixin
    
    # do_package(13) #远程仓库
    
    db.close()
    
    pass